﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace The_LarX
{
    public class VisualScript : Component
    {
        public List<VisualScript_Node> Nodes;

        public VisualScript(GameScreen Screen)
            : base(Screen)
        {
            this.DeserializeAfter = true;
            Load();
        }
        public VisualScript()
        {
            this.DeserializeAfter = true;
            Load();
        }

        private void Load()
        {
            EngineSystem.VisualScripts.Add(this);
            Nodes = new List<VisualScript_Node>();
        }

        private bool called;
        public override void Update()
        {
            base.Update();

            if (!Engine.PlayMode)
            {
                called = false;
                for (int i = 0; i < Nodes.Count; i++)
                {
                    Nodes[i].Update();
                }
            }
            else
            {
                if (!called)
                {
                    for (int i = 0; i < Nodes.Count; i++)
                    {
                        Nodes[i].PlayModeFalse();
                    }
                    called = true;
                }
            }
        }

        public override void Draw()
        {
            base.Draw();

            for (int i = 0; i < Nodes.Count; i++)
            {
                Nodes[i].Draw();
            }
        }

        public override void SerializeData()
        {
            base.SerializeData();

            for (int i = 0; i < Nodes.Count; i++)
            {
                Nodes[i].SerializeData(Data);
                Data.AddData(Nodes[i].CreatedNumber + "Type", Nodes[i].GetType().FullName);
            }
            Data.AddData("NodesCount", Nodes.Count);
        }
        public override void DeserializeData()
        {
            base.DeserializeData();

            int nodesCount = Data.GetData<int>("NodesCount");
            for (int i = 0; i < nodesCount; i++)
            {
                string type = Data.GetData<string>(i + "Type");
                Type tipo = Type.GetType(type);
                VisualScript_Node node = (VisualScript_Node)Activator.CreateInstance(tipo);
                Nodes.Add(node);
                node.Script = this;
            }
            for (int i = 0; i < Nodes.Count; i++)
            {
                Nodes[i].DeserializeData(Data);
            }
        }
    }
}
